package com.year.shiyi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.year.shiyi.entity.mybatis.SysRoleMenuEntity;
import com.year.shiyi.mapper.SysRoleMenuMapper;
import com.year.shiyi.service.SysRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色与菜单对应关系 服务实现类
 * </p>
 *
 * @author shiyi
 * @since 2021-03-03
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenuEntity> implements SysRoleMenuService {

    @Override
    public List<Long> queryMenuIdList(Long roleId) {
        QueryWrapper<SysRoleMenuEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        return this.list(wrapper).stream().map(SysRoleMenuEntity::getMenuId).collect(Collectors.toList());
    }

    @Override
    public boolean saveOrUpdate(Long roleId, List<Long> menuIdList) {
        deleteBatch(roleId);
        if (menuIdList.size() == 0) {
            return true;
        }
        List<SysRoleMenuEntity> list = new ArrayList<>();
        for (Long menuId : menuIdList) {
            SysRoleMenuEntity entity = new SysRoleMenuEntity();
            entity.setMenuId(menuId);
            entity.setRoleId(roleId);
            list.add(entity);
        }
        return this.saveBatch(list);
    }

    private void deleteBatch(Long roleId) {
        Map<String, Object> param = new HashMap<>();
        param.put("role_id", roleId);
        this.removeByMap(param);
    }
}
